function useWebSocket(userId, options = {}) {
    // 定义重复连接次数以及重连间隔时长
    const { reconnectInterval = 3000, maxReconnectAttempts = 5 } = options;

    // 连接状态
    let isConnect = false;
    // 重新连接次数
    let reconnectAttempts = 0;
    // 服务端URL
    const socketServer = `ws://localhost:8765/websocket/message?userId=${userId}`;

    // 创建socket实例
    const socket = new WebSocket(socketServer);

    // 事件监听器
    const messageListeners = new Set();

    const connect = () => {
        // 打开事件
        socket.onopen = () => {
            isConnect = true;
            reconnectAttempts = 0;
            console.log('WebSocket连接已打开！');
        };
        // 收到消息事件
        socket.onmessage = (event) => {
            messageListeners.forEach(listener => listener(event.data));
        };
        // 关闭事件
        socket.onclose = () => {
            isConnect = false;
            console.log('WebSocket连接已关闭');
            if (reconnectAttempts < maxReconnectAttempts) {
                reconnectAttempts += 1;
                console.log(`尝试重新连接 (${reconnectAttempts}/${maxReconnectAttempts})`);
                setTimeout(connect, reconnectInterval);
            } else {
                console.log('达到最大连接次数，停止连接');
            }
        };
        socket.onerror = (error) => {
            console.error('WebSocket 错误:', error);
        };
    };

    connect();

    const sendSocketMessage = (message) => {
        if (isConnect && message) {
            socket.send(message);
        }
    };

    const addMessageListener = (listener) => {
        messageListeners.add(listener);
    };

    const removeMessageListener = (listener) => {
        messageListeners.delete(listener);
    };

    return {
        isConnect,
        sendSocketMessage,
        addMessageListener,
        removeMessageListener
    };
}

module.exports = {
    useWebSocket
  }
  